package com.wbt.juc.threadpool;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThreadPool {

    private static int num = 0;
    public static void main(String[] args) {
        ArrayBlockingQueue queue = new ArrayBlockingQueue<>(5);
        ExecutorService threadPool = new ThreadPoolExecutor(4,8,30,
                TimeUnit.SECONDS,queue);

        //int num = 0;

        for (int i = 0; i < 10; i++) {
            num = i;
            threadPool.execute(()->{
                try {
                    System.out.println(currentThreadName() + ", "+ num + " running, " + System.currentTimeMillis());

                   // Thread.sleep(2000);
                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis()-start <= 5000){

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            System.out.println("pool:" + queue.size());
        }

        while (true){
            if(queue.size() == 0){
                for (int i = 0; i < (int) (Math.random()*20); i++) {
                    num = num + i;
                    threadPool.execute(()->{
                        try {
                            System.out.println(currentThreadName() + ", "+ num + " running, " + System.currentTimeMillis());

                            //Thread.sleep(2000);
                            long start = System.currentTimeMillis();
                            while (System.currentTimeMillis()-start <= 5000){

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                    System.out.println("pool:" + queue.size());
                }

            }
        }

       // threadPool.shutdown();

    }
    private static String currentThreadName() {
        return Thread.currentThread().getName();
    }
}
